<template>
  <basic-container>
    <avue-crud :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleView(scope.row)">查看
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 增</el-button>
        <!-- <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.invoice_mail_delete"
                   @click="handleDelete">删 除
        </el-button> -->
      </template>
      <template slot="menuRight">
        <!-- <el-button type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.invoice_mail_import"
          @click="handleImport">导入
        </el-button> -->
        <!-- <el-button type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport">导出
        </el-button> -->
      </template>
    </avue-crud>
    <!-- 新建 -->
    <el-dialog
      :title="dialogText"
      top="1%"
      append-to-body
      :close-on-press-escape='false'
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      :before-close="handleClose">
      <el-form :model="mainForm" v-loding="mainFormLoding" :rules="mainFormRules" ref="mainForm" v-loading="loading" size="small" label-width="150px">
        <el-row :gutter="20" style="margin-bottom:20px;">
          <el-col :span="24">
            <el-alert
              title="注意事项"
              type="warning"
              :description="noteData.note1"
              v-show="noteData.note1">
            </el-alert>
          </el-col>
          <el-col :span="24">
            <el-alert
              title="注意事项"
              type="warning"
              :description="noteData.note2"
              v-show="noteData.note2">
            </el-alert>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="服务商" prop="userNo">
              <el-select class="invoiceType" filterable size="small" v-model="mainForm.userNo" placeholder="请选择服务商">
                <el-option
                  v-for="item in userNoTypelist"
                  :key="item.id"
                  :label="item.serviceName"
                  :value="item.userNo"
                >
                  <span style="float: left">{{ item.serviceName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="邮寄地址" prop="riAddress">
              <el-input v-model.trim="mainForm.riAddress" size="small" placeholder="请输入邮寄地址" maxlength="250"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select class="invoiceType" size="small" v-model="mainForm.invoiceType" placeholder="请选择发票类型">
                <el-option
                  v-for="item in invoiceTypeOptions"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="mainForm.invoiceType != 1">
            <el-form-item label="物流单号" prop="rimMailNo">
              <el-input v-model.trim="mainForm.rimMailNo" size="small" placeholder="请输入物流单号" maxlength="15"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮寄时间" prop="emailTime">
              <el-date-picker
                class="haruyuki-width-100"
                type="date"
                v-model="mainForm.emailTime"
                placeholder="请选择邮寄时间"
                value-format="yyyy-MM-dd"
                style="width:100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button type="primary" @click="addBtn" size="small">新增</el-button>
          </el-col>
          <div v-for="(item,index) in mainForm.list" :key="item.index" @click.stop="clickIndex(index)">
            <el-col :span="22">
              <el-form-item 
                label="上传发票图片:"
                :prop="'list.'+index+'.link'"
                :rules="{
                  required: true, message: '请上传发票图片', trigger: 'blur'
                }"
              >
                <el-upload
                  action="/api/blade-resource/oss/endpoint/put-file-attach"
                  list-type="picture-card"
                  :http-request="httpRequestFp"
                  :limit="1"
                  :file-list="item.fileListFp"
                  :on-remove="onRemoveFp"
                  :before-remove="beforeonRemoveFp"
                  :on-exceed="handHeldExceed"
                  :before-upload="beforeUpload"
                  :on-preview="imgPreview"
                >
                  <i slot="default" class="el-icon-plus"></i>
                </el-upload>
            </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="发票号" :prop="'list.'+index+'.invoiceCode'" :rules="{ required: true, message: '发票号不能为空', trigger: 'blur'}">
                <el-input v-model.trim="item.invoiceCode" placeholder="请输入发票号" maxlength="30"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="发票金额" :prop="'list.'+index+'.amount'" :rules="{ required: true, message: '发票金额不能为空', trigger: 'blur'}">
                <el-input v-model="item.amount" controls-position="right" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" @change="handleChange" placeholder="请输入发票金额" maxlength="12" size="small" ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="danger" @click="deleteBtn(index)" v-show="mainForm.list.length >1" size="small">删除</el-button>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { dialogVisible = false; initEmpty(); }">取 消</el-button>
        <el-button type="primary" v-preventClick @click="mainFormSubmit()" :disabled="mainFormLoding">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片查看 -->
    <el-image-viewer
        style="z-index: 99999;"
        v-if="imgShow"
        :on-close="()=>{ imgShow = false }"
        :url-list="imgUrlList"
      ></el-image-viewer>
  </basic-container>
</template>

<script>
import { getList, add, getExport, getExportTemplate,getNote,invoiceType} from "@/api/rb-oem/invoiceMail/invoice_mail";
import { mapGetters } from "vuex";
import { uploadPublic } from "@/api/system/oss";
import { userNoTypelist } from "@/api/rb-oem/wallet/user_wallet";
import { downloadFileExcel } from "@/util/util";
import canvasImg from '@/util/canvasImg';

export default {
  mixins: [canvasImg],
  data() {
    return {
      imgShow:false,
      imgUrlList:[],
      form: {},
      query: {},
      search: {},
      dialogVisible: false,
      dialogText: '',
      loading: true,
      excelBox: false,
      invoiceTypeOptions: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      mainForm: {
        invoiceType:"",
        list: [{
          invoiceCode: '',
          amount: '',
          link:'',
          fileListFp:[]//上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
        }]
      },
      indexNum:0,//发票个数索引
      mainFormRules: {
        userNo: [
          {required: true, message: "请选择服务商", trigger: "change"},
        ],
        riAddress: [
          {required: true, message: "请输入邮寄地址", trigger: "blur"},
        ],
        invoiceType: [
          {required: true, message: "请选择邮寄类型", trigger: "change"},
        ],
        rimMailNo: [
          {required: true, message: "请输入物流单号", trigger: "blur"},
        ],
        emailTime: [
          {required: true, message: "请选择时间", trigger: ["blur","change"]},
        ]
      },
      selectionList: [],
      option: {
       height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        addBtn: false,
        editBtn:false,
        delBtn:false,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth:120,        //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        column: [
          {
            label: "服务商编号",
            prop: "userNo",
            type: "input",
            //sortable: true,
            search: false,
            rules: [{
              required: true,
              message: "请输入oem编号",
              trigger: "blur"
            }],
            minWidth:110,
            overHidden:true,
          },
          {
            label: "服务商名称",
            prop: "userName",
            type: 'select',
            width: 200,
            search: false,
            props: {
              label: "serviceName",
              value: "userNo",
              desc:'userNo',
            },
            filterable:true,
            dicData: [],
            dicFormatter:(data)=>{
              return data.data.records
            },
            // overHidden: true,
          },
          {
            label: "物流单号",
            prop: "rimMailNo",
            type: "input",
            //sortable: true,
            search: true,
            minWidth:140,
            overHidden: true,
          },
          {
            label: "合计金额",
            prop: "payTotalPrice",
            type: "input",
            search: true,
            //sortable: true,
            overHidden: true,
          },
          {
            label: "审核金额",
            prop: "examimePrice",
            type: "input",
            search: true,
            //sortable: true,
            overHidden: true,
          },
          {
            label: "邮寄时间",
            //sortable: true,
            prop: "emailTimeShort",
            type: "datetime",
            search: false,
            overHidden: true,
          },
          {
            label: "邮寄时间段",
            prop: "emailTimeData",
            type: 'datetimerange',
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '邮寄时间开始时间',
            endPlaceholder: '邮寄时间结束时间',
            search: true,
            rules: [{
              required: true,
              message: "请选择邮寄时间段",
              trigger: "blur"
            }],
            hide:true,
            display:false,
            overHidden: true,
          },
          {
            label: "发票类型",
            prop: "invoiceType",
            type: "select",
            dataType: 'number',
            //sortable: true,
            search: true,
            rules: [{
              required: true,
              message: "请输入发票类型",
              trigger: "blur"
            }],
            dicUrl: '/api/blade-system/dict/dictionary?code=invoice_type',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
          },
          {
            label: "审核状态",
            prop: "adminState",
            type: "select",
            dataType: 'number',
            //sortable: true,
            search: true,
            rules: [{
              required: true,
              message: "请输入发票类型",
              trigger: "blur"
            }],
            dicUrl: '/api/blade-system/dict/dictionary?code=admin_state',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
          },
          {
            label: "审核意见",//
            prop: "remark",
            type: "textarea",
            search: false,
            //sortable: true,
            overHidden: true
          }  
        ]
      },
      data: [],
      userNoTypelist:[],
      mainFormLoding:false,
      noteData:{},
      // querDisable:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.invoice_mail_add, false),
        viewBtn: this.vaildData(this.permission.invoice_mail_view, false),
        delBtn: this.vaildData(this.permission.invoice_mail_delete, false),
        editBtn: this.vaildData(this.permission.invoice_mail_edit, false),
        exportBtn: this.vaildData(this.permission.invoice_mail_export, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created(){
    this.note();
    this.getInvoiceType();
    // this.getUserNoTypelist();
  },
  methods: {
    // 获取发票类型
    getInvoiceType(){
      invoiceType().then(res=>{
        this.invoiceTypeOptions = res.data.data;
        const column = this.findObject(this.option.column, "invoiceType");
        column.dicData = this.invoiceTypeOptions;
      })
    },
    // 获取注意事项
    note(){
      getNote().then(res=>{
        this.noteData = res.data.data;
      })
    },
    // 发票图片点击哪一个
    clickIndex(index){
      this.indexNum = index;
    },
    // 获取服务商
    getUserNoTypelist(){
      userNoTypelist().then(res=>{
        this.userNoTypelist=res.data.data.records;
        const column = this.findObject(this.option.column, "userName");
        column.dicData = this.userNoTypelist;
      })
    },
    /* 文件超出个数限制时的钩子 */
    handHeldExceed() {
      this.$message.error("只能上传一张图片哦~");
    },
    /* 发票图片上传 */
    httpRequestFp(option){
      let _this = this;
      uploadPublic(option.file, option.file.name).then((res) => {
        _this.mainForm.list[_this.indexNum].link = res.data.data.link;
        
        // 回显用
        // _this.mainForm.list[_this.indexNum].fileListFp.push({
        //   url:res.data.data.link,
        //   name:res.data.data.originalName
        // })
      });
    },
    /* 发票图片删除 */
    onRemoveFp(file, fileList){
      this.mainForm.list[this.indexNum].fileListFp = fileList;
      this.mainForm.list[this.indexNum].link="";
    },
    // 图片删除前回调
    beforeonRemoveFp() {
      return this.$confirm(`确定移除这张发票图片？`);
    },
    /* 预览图片 */
    imgPreview(file) {
      this.imgUrlList[0] = file.url;
      this.imgShow = true;
    },
    /* 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传 */
    // beforeUpload(file) {
    //   this.compressPictures(file);
    // },
    // 新增 发票图片list
    addBtn() {
      this.mainForm.list.push(//增加就push进数组一个新值
        {
          invoiceCode: '',
          amount: '',
          link:'',
          fileListFp:[]
        }
      )
    },
    deleteBtn(index) {
      if (this.mainForm.list.length <= 1) {//如果只有一个输入框则不可以删除
        return false
      }
      this.mainForm.list.splice(index, 1)//删除了数组中对应的数据也就将这个位置的输入框删除
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.dialogVisible = true;
      this.dialogText = '邮寄发票';
    },
    /* 新建发票记录---保存提交 */
    mainFormSubmit() {
      this.$refs['mainForm'].validate((valid) => {
        if (valid) {
          this.mainFormLoding=true;
          if(this.mainForm.emailTime.length === 10){
            this.mainForm.emailTime = this.mainForm.emailTime + " 00:00:00";
          }
          add(this.mainForm).then(() => {
            // this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.dialogVisible=false;
            this.initEmpty();
          }, error => {
            this.mainFormLoding=false;
            window.console.log(error);
          });
        }else{
          this.mainFormLoding=false;
        }
      })
    },
    handleClose(done) {
      this.initEmpty();
      done();
    },
    initEmpty() {
      this.$refs['mainForm'].resetFields();
      this.indexNum=0;
      // this.mainForm.list = [{
      //     invoiceCode: '',
      //     amount: '',
      //     link:'',
      //     fileListFp:[]
      //   }]
      this.mainFormLoding=false;
      this.onLoad(this.page);
    },
    // handleDelete() {
    //   if (this.selectionList.length === 0) {
    //     this.$message.warning("请选择至少一条数据");
    //     return;
    //   }
    //   this.$confirm("确定将选择数据删除?", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       return remove(this.ids);
    //     })
    //     .then(() => {
    //       this.onLoad(this.page);
    //       this.$message({
    //         type: "success",
    //         message: "操作成功!"
    //       });
    //       this.$refs.crud.toggleSelection();
    //     });
    // },
    handleView(row) {
      this.$router.push({
        path: '/invoiceMail/invoice_mail_details',
        query: {
          rimNo: row.rimNo,
        },
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      // 邮寄时间段
      if(params.emailTimeData){
        params.beginEmailTime = params.emailTimeData[0];
        params.endEmailTime = params.emailTimeData[1];
      }

      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }, 
    // 导入 功能带完善
    handleImport() {
      this.excelBox = true;
    },
    // 导出
    handleExport() {
      if(this.search.emailTimeData){
        this.search.beginEmailTime = this.search.emailTimeData[0];
        this.search.endEmailTime = this.search.emailTimeData[1];
      }
      
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        getExport(this.search).then((res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    // 下载模板
    handleTemplate() {
       getExportTemplate().then((res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    // 删除图片前回调
    uploadDelete(){
      return this.$confirm('是否确定移除该选项？');
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop
        this.query.descs = ""
      } else {
        //倒序
        this.query.descs = val.prop
        this.query.ascs = ""
      }
      this.refreshChange();
    }
  }
};
</script>

<style scoped lang="scss">
.invoiceType{
  width: 100% !important;
}
</style>
